package com.lagou.utils;

import com.lagou.bean.ExecTime;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class Statistics implements Runnable {
    private LinkedList<ExecTime> queue;
    private String methodName;

    public Statistics(LinkedList<ExecTime> queue, String methodName) {
        this.queue = queue;
        this.methodName=methodName;
    }
    LinkedList<Long> longs;
    int count=0;

    public void run() {
        count++;
        longs = new LinkedList<Long>();
        //当前时间点
        long nowtime = System.currentTimeMillis();
        long minuteBefore = nowtime - 60000;//1分钟之前
        long wwBefore = nowtime - 55000;//55秒之前

        Iterator<ExecTime> it = queue.iterator();
        while (it.hasNext()){
            ExecTime et = it.next();
            long pts = et.getTimestamp();
            long etime = et.getExectime();
            if(pts < minuteBefore){
                it.remove();
            }else if(minuteBefore <=pts && pts < wwBefore){
                longs.add(etime);
                it.remove();
            }else if(wwBefore <= pts && pts < nowtime){
                longs.add(etime);
            }else{
                break;
            }
        }
        Collections.sort(longs);
        int _90 = (int)(longs.size() * 0.90);
        int _99 = (int)(longs.size() * 0.99);

        String format = String.format("%s %d次统计 | 分钟请求 %d 次 | tp90 ==> %d | tp99 ==> %d",methodName,count,longs.size(),longs.get(_90),longs.get(_99));
        System.out.println(format);
    }
}
